import axios from 'axios';

export class AIProvider {
  constructor(modelConfigs) {
    this.configs = modelConfigs.configs;
    this.currentModel = modelConfigs.default;
    this.tools = [];
  }

  setTools(tools) {
    this.tools = tools;
  }

  getCurrentModel() {
    return this.currentModel;
  }

  switchModel(modelName) {
    if (this.configs[modelName]) {
      this.currentModel = modelName;
      return true;
    }
    return false;
  }

  async chat(messages) {
    const config = this.configs[this.currentModel];
    if (!config) {
      throw new Error(`未知的模型配置: ${this.currentModel}`);
    }

    switch (this.currentModel) {
      case 'openai':
      case 'custom':
        return await this.chatOpenAI(messages, config);
      case 'claude':
        return await this.chatClaude(messages, config);
      default:
        throw new Error(`不支持的模型类型: ${this.currentModel}`);
    }
  }

  async chatOpenAI(messages, config) {
    try {
      const payload = {
        model: config.model,
        messages: messages,
        max_tokens: config.max_tokens,
        temperature: config.temperature
      };

      // 如果有工具，添加工具调用
      if (this.tools.length > 0) {
        payload.tools = this.tools;
        payload.tool_choice = 'auto';
      }

      // 修改点：直接使用config.base_url作为完整请求地址，不再额外拼接/chat/completions
      const response = await axios.post(
        config.base_url,  // 原代码为`${config.base_url}/chat/completions`
        payload,
        {
          headers: {
            'Authorization': `Bearer ${config.api_key}`,
            'Content-Type': 'application/json'
          }
        }
      );

      const choice = response.data.choices[0];
      
      if (choice.message.tool_calls) {
        return {
          content: choice.message.content,
          tool_calls: choice.message.tool_calls
        };
      }

      return {
        content: choice.message.content
      };

    } catch (error) {
      if (error.response) {
        throw new Error(`API 错误: ${error.response.data.error?.message || error.response.statusText}`);
      }
      throw new Error(`网络错误: ${error.message}`);
    }
  }

  async chatClaude(messages, config) {
    try {
      // 转换消息格式为 Claude 格式
      const claudeMessages = this.convertToClaudeFormat(messages);
      
      const payload = {
        model: config.model,
        max_tokens: config.max_tokens,
        temperature: config.temperature,
        messages: claudeMessages
      };

      // Claude 的工具调用格式
      if (this.tools.length > 0) {
        payload.tools = this.tools.map(tool => ({
          name: tool.function.name,
          description: tool.function.description,
          input_schema: tool.function.parameters
        }));
      }

      const response = await axios.post(
        `${config.base_url}/messages`,
        payload,
        {
          headers: {
            'x-api-key': config.api_key,
            'Content-Type': 'application/json',
            'anthropic-version': '2023-06-01'
          }
        }
      );

      const content = response.data.content[0];
      
      if (content.type === 'tool_use') {
        return {
          content: response.data.content.find(c => c.type === 'text')?.text || '',
          tool_calls: response.data.content
            .filter(c => c.type === 'tool_use')
            .map(c => ({
              id: c.id,
              type: 'function',
              function: {
                name: c.name,
                arguments: JSON.stringify(c.input)
              }
            }))
        };
      }

      return {
        content: content.text
      };

    } catch (error) {
      if (error.response) {
        throw new Error(`Claude API 错误: ${error.response.data.error?.message || error.response.statusText}`);
      }
      throw new Error(`网络错误: ${error.message}`);
    }
  }

  convertToClaudeFormat(messages) {
    // Claude 不支持 system 消息在消息数组中，需要特殊处理
    const claudeMessages = [];
    
    for (const msg of messages) {
      if (msg.role === 'system') {
        // 将 system 消息转换为第一个 user 消息的前缀
        if (claudeMessages.length === 0) {
          claudeMessages.push({
            role: 'user',
            content: `System: ${msg.content}\n\nUser: Please follow the system instructions above.`
          });
        }
      } else if (msg.role === 'tool') {
        // 工具结果消息
        claudeMessages.push({
          role: 'user',
          content: [
            {
              type: 'tool_result',
              tool_use_id: msg.tool_call_id,
              content: msg.content
            }
          ]
        });
      } else {
        claudeMessages.push({
          role: msg.role === 'assistant' ? 'assistant' : 'user',
          content: msg.content
        });
      }
    }
    
    return claudeMessages;
  }

  // 创建系统提示，包含可用工具的信息
  createSystemPrompt() {
    let systemPrompt = `你是一个智能助手，可以使用多种工具来帮助用户完成任务。

可用工具:
`;

    this.tools.forEach(tool => {
      systemPrompt += `- ${tool.function.name}: ${tool.function.description}\n`;
    });

    systemPrompt += `
请根据用户的请求，合理选择和使用这些工具。如果需要多个步骤，请逐步执行。
在使用工具时，请确保参数格式正确。
`;

    return systemPrompt;
  }

  // 获取增强的消息（包含系统提示）
  getEnhancedMessages(userMessages) {
    const systemPrompt = this.createSystemPrompt();
    return [
      { role: 'system', content: systemPrompt },
      ...userMessages
    ];
  }
}